#include <string>
#include <iostream>
#include "Parser.hpp"
#include "ClientList.h"

Parser::Parser()
{
  this->_ClientList = new ClientList;
}

Parser::~Parser()
{

}

std::string	Parser::getNextWord()
{
  std::string	tmp = this->_data.substr(this->_pos, (this->_data.find(" ", this->_pos) - this->_pos));
  this->_pos = this->_data.find(" ", this->_pos) + 1;
  return (tmp);
}

void	Parser::heloHandler()
{
  std::cout << "Hello from :" << getNextWord() << std::endl;
  this->_ClientList->manageData(this->_data, this->_id);
  this->_ClientList->incIndex(_id);
}

void	Parser::fromHandler()
{
  if (getNextWord() == "FROM:")
    {
      std::cout << "Message sent by:" << getNextWord() << std::endl;
      this->_ClientList->manageData(this->_data, this->_id);
      this->_ClientList->incIndex(_id);
    }
}

void	Parser::toHandler()
{
  if (getNextWord() == "TO:")
    {
      std::cout << "Message sent to:" << getNextWord() << std::endl;
      this->_ClientList->manageData(this->_data, this->_id);
      this->_ClientList->incIndex(this->_id);
    }
}

void	Parser::dataHandler()
{
  std::cout << "Data incoming\n========================\n" << std::endl;
  this->_ClientList->manageData(this->_data, this->_id);
  this->_ClientList->incIndex(this->_id);
}

void	Parser::quitHandler()
{
  std::cout << "Closing connection..." << std::endl;
}

void	Parser::bodyHandler()
{
  std::string tmp = getNextWord();
  if (this->_data == ".")
    {
      // 	  this->_ClientList->stockMail(_id);
      std::cout << "Saving mail..." << std::endl;
    }
  else
    {
      std::cout << "adding data to mail body..." << std::endl;
      this->_ClientList->manageData(this->_data, this->_id);
    }
}

void	Parser::Parse(int id, std::string data)
{
  this->_pos = 0;
  if (id > 0)
    this->_id = id;
  if (!data.empty())
    this->_data = data;

  std::string tmp =  getNextWord();
  if (tmp == "HELO")
    heloHandler();
  else if (tmp == "MAIL")
    fromHandler();
  else if (tmp == "RCPT")
    toHandler();
  else if (tmp == "DATA")
    dataHandler();
  else if (tmp == "quit")
    quitHandler();
  else
    bodyHandler();
  _data = "";
  _id = -1;
}
